// lib/api.ts
const API_BASE_URL = 'http://localhost:8080/vote.VoteService';

export interface Option {
  id: string;
  text: string;
  votes: number;
}

export interface VoteRequest {
  optionId: string;
}

export interface VoteResponse {
  success: boolean;
  message: string;
}

export interface ResultsResponse {
  topic: string;
  options: Option[];
}

export async function getResults(): Promise<ResultsResponse> {
  console.log(`${API_BASE_URL}/GetResults`);
  const response = await fetch(`${API_BASE_URL}/GetResults`, {
    method: 'POST',
    body: JSON.stringify({}),
    headers: {
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    throw new Error(`获取结果失败: ${response.status}`);
  }

  return response.json();
}

export async function vote(optionId: string): Promise<VoteResponse> {
  console.log(`${API_BASE_URL}/Vote`);
  const response = await fetch(`${API_BASE_URL}/Vote`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ optionId }),
  });

  if (!response.ok) {
    throw new Error(`投票失败: ${response.status}`);
  }
  const result = await response.json(); // 使用 await 等待 Promise 解析完成
  console.log(result); // 打印解析后的结果
  return result; // 返回解析后的结果
}